package avicit.bdp.dms.oauth2.validator;

import avicit.bdp.dms.oauth2.token.AccessToken;
import avicit.bdp.dms.oauth2.token.JWTOauthUtils;
import avicit.bdp.dms.tdm.dto.AppClientDTO;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO
 *
 * @author xugb
 * @date 2024/4/12 15:12
 */

public class RefreshTokenClientDetailsValidator extends AbstractOauthTokenValidator {
    private static final Logger LOG = LoggerFactory.getLogger(RefreshTokenClientDetailsValidator.class);

    public RefreshTokenClientDetailsValidator(OAuthTokenRequest oauthRequest) {
        super(oauthRequest);
    }

    @Override
    protected OAuthResponse validateSelf(AppClientDTO appClientDTO) throws OAuthSystemException {

        String clientSecret = this.oauthRequest.getClientSecret();
        if (clientSecret != null && clientSecret.equals(appClientDTO.getClientSecret())) {
            String refreshToken = this.tokenRequest.getRefreshToken();

            try {
                JWTOauthUtils.verifyRefreshToken(refreshToken);
                DecodedJWT jwtRefresh = JWTOauthUtils.decodeToken(refreshToken);
                String refreshTokenId = jwtRefresh.getId();
                AccessToken assertToken = this.oauthService.getAccessTokenByRefreshToken(refreshTokenId, this.oauthRequest.getClientId());
                return assertToken == null ? this.invalidRefreshTokenResponse(refreshToken) : null;
            } catch (Exception var8) {
                LOG.debug("Invalid refresh_token: '{}'", refreshToken);
                return this.invalidRefreshTokenResponse(refreshToken);
            }
        } else {
            LOG.debug("Invalid client_secret '{}', client_id = '{}'", clientSecret, appClientDTO.getClientId());
            return this.invalidClientSecretResponse();
        }

    }

    private OAuthResponse invalidRefreshTokenResponse(String refreshToken) throws OAuthSystemException {
        return OAuthResponse.errorResponse(400).setError("invalid_grant").setErrorDescription("Invalid refresh_token: " + refreshToken).buildJSONMessage();
    }
}
